package br.com.bankai.koby.presentation.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import br.com.bankai.koby.presentation.security.UserInfo;
import br.com.bankai.koby.repository.entity.simple.UsuarioSimple;

/**
 * 
 * @author Leonardo
 *
 */
public class SessionUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(SessionUtil.class);

	public static UsuarioSimple getAuthenticatedUsuario() {
		UserInfo userInfo = getAuthenticatedUser();

		if (null != userInfo) {
			return userInfo.getUsuario();
		}

		return null;
	}

	public static String getSourceAddress() {
		UserInfo userInfo = getAuthenticatedUser();

		if (null != userInfo) {
			return userInfo.getSourceAddress();
		}
		return "";
	}

	public static UserInfo getAuthenticatedUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (null != authentication && authentication instanceof UsernamePasswordAuthenticationToken) {
			UserInfo user = (UserInfo) ((UsernamePasswordAuthenticationToken) authentication).getPrincipal();
			return user;
		} else {
			LOGGER.debug("Anonymous user");
			return null;
		}
	}

	public static boolean isPapel(String codigo) {
		return ((UsuarioSimple) SessionUtil.getAuthenticatedUsuario()).getCodigoPapel().equals(codigo);
	}
}